import json

class Transaction:
    """
    交易的结构
    """
    def __init__(self, sender, recipient, amount):
        """
        初始化交易
        :param sender: 交易发送方
        :param recipient: 接收方
        :param amount: 交易金额
        """
        if isinstance(sender, bytes):
            sender = sender.decode('utf-8')
        # 发送方
        self.sender = sender
        if isinstance(recipient, bytes):
            recipient = recipient.decode('utf-8')
        # 接收方
        self.recipient = recipient
        # 交易数量
        self.amount = amount

    def set_sign(self, signature, pubkey):
        """
        为了便于验证交易的可靠性，需要发送方输入他的公钥的签名
        :param signature:  签名
        :param pubkey: 发送方公钥
        """
        self.signature = signature
        self.pubkey = pubkey

    def __repr__(self):
        """
        交易大致分为两种，一是挖矿所得，二是转账交易
        挖矿所得无法送方，一次进行区分显示不同内容
        """
        if self.sender:
            s = "从 %s 转至 %d 个加密货币" % (self.sender, self.recipient, self)
        else:
            s = "%s 挖矿获取 %d 个加密货币" %(self.recipient, self.amount)
        return s

    


